/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package crowler;

import beans.ejb.NflplayergameFacade;
import beans.managed.Crowler;
import entities.Nflplayer;
import entities.Nflplayergame;
import entities.Nflplayerseasonstat;
import entities.Nflteam;
import entities.Week;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.xml.bind.JAXBException;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

/**
 *
 * @author The Lunatics
 */
@ManagedBean
@ApplicationScoped
public class PlayerGameCrowler extends CrowlerEssentials {

    private List<entities.Nflplayergame> playergames;
    @EJB
    private NflplayergameFacade playerGamesFacade;
    public static String APIURL = Crowler.APIURL;
    public static String TESTURL = Crowler.TESTURL;
    

    public PlayerGameCrowler() throws ParserConfigurationException {
    }

    public String queryAPlayerGameStatByPlayerIdFromWeekId(String weekId, Nflplayer player) throws IOException {
        System.err.println("queryAllPlayerGameStatByPlayerIdFromWeek: " + weekId + " : " + player.getId());

        String season = weekId.substring(0, 4);
        String week = Integer.toString(new Integer(weekId.substring(4, 6)));
        return queryAPlayerGameStatByPlayerId(season, week, player);
    }

    public String queryAPlayerGameStatByPlayerIdFromWeekIdToTheEnd(String weekId, Nflplayer player) throws IOException {
        System.err.println("queryAllPlayerGameStatByPlayerIdFromWeek: " + weekId + " : " + player.getId());

        String season = weekId.substring(0, 4);
        String week = Integer.toString(new Integer(weekId.substring(4, 6)));
        Integer weekInt = new Integer(week);
        for (int i = weekInt; i <= 16; i++) {
            queryAPlayerGameStatByPlayerId(season, Integer.toString(i), player);
        }
        return returnPage;
    }

    public String queryAPlayerGameStatByPlayerId(String weekId, Nflplayer player) throws IOException {
        System.err.println("queryAllPlayerGameStatByWeek: " + weekId + " : " + player.getId());

        String season = weekId.substring(0, 4);
        String week = Integer.toString(new Integer(weekId.substring(4, 6)));
        return queryAPlayerGameStatByPlayerId(season, week, player);
    }

    public String queryAPlayerGameStatByPlayerId(String season, String week, Nflplayer player) throws IOException {
        System.err.println("queryAllPlayerGameStatByWeek: " + week + " : " + player.getId());        //http://test.nfldata.com/api.svc/xml/PlayerGameStatsByPlayerID/2011/1/2593?key=c7fb0f65-ccb4-4965-bbb9-4cecd0890e10
        URL url = new URL(APIURL + "/xml/PlayerGameStatsByPlayerID/" + season + "/" + week + "/" + player.getId() + "?key=" + licensekey);
        System.err.println(url);
        Document doc = request(url, "GET", null);
        if (playergames == null) {
            playergames = new ArrayList();
        }
        NodeList gameNodes = doc.getElementsByTagName("PlayerGame");
        Nflplayergame playergame;
        try {
            Element element = (Element) gameNodes.item(0);
            if (element == null) {
                return returnPage;
            }
            playergame = createNflplayergameFromElement(element);
            Integer playerId = getIntegerAsName(element, "PlayerID");

            if (playerId != player.getId()) {
                System.err.println("PlayerId In game:" + playerId + " playerId: " + player.getId());
            }
            playergame.setPlayerId(player);

            // Find and set team by key 
            String teamKey = getTextAsName(element, "Team");
            for (Iterator<Nflteam> it = teams.iterator(); it.hasNext();) {
                Nflteam nflteam = it.next();
                if (nflteam.getKeyCode().equals(teamKey)) {
                    playergame.setTeamId(nflteam);
                    break;
                }
            }
            // Find and Set Game By GameId
            // TODO: There is no game data from nfldata.com! 


            // Set WeekID
            String weekIdStr;
            if (week.length() < 2) {
                weekIdStr = season.concat("0" + week);
            } else {
                weekIdStr = season.concat(week);
            }
            Integer weekIdInt = new Integer(weekIdStr);
            playergame.setWeekId(new Week(weekIdInt));

            playergames.add(playergame);
            if (playerGamesFacade.find(playergame.getId()) == null) {
                playerGamesFacade.create(playergame);
            }

        } catch (JAXBException ex) {
            Logger.getLogger(Crowler.class.getName()).log(Level.SEVERE, null, ex);
        }
        return returnPage;
    }

    public String queryAllPlayerGameStatsByPlayerId() throws IOException {
        String playerId = null;
        for (int i = 0; i < players.size(); i++) {
//            if (i > 10) {
//                break;
//            }
            Nflplayer player = players.get(i);
            queryAPlayerGameStatByPlayerId(weekId, player);
        }
        return returnPage;
    }
    
    public String filterPlayerGameStatByPosition() {
        playergames = playerGamesFacade.findAll();
        for (Iterator<Nflplayergame> it = playergames.iterator(); it.hasNext();) {
            Nflplayergame playergame = it.next();
            Nflplayer targetPlayer = playergame.getPlayerId();
            if (targetPlayer == null || !isAllowedPosition(targetPlayer.getPosition())) {
                System.err.append("Remove Player Game for :" + playerId);
                playerGamesFacade.remove(playergame);
            }
        }
        return returnPage;
    }

    private Nflplayergame createNflplayergameFromElement(Element element) throws JAXBException {
        Nflplayergame nflPlayerGame = (Nflplayergame) unmarshallXMLToObject(element, Nflplayergame.class);
        System.err.println(nflPlayerGame);
        return nflPlayerGame;
    }

    public List<Nflplayergame> getPlayergames() {
        return playergames;
    }

    public void setPlayergames(List<Nflplayergame> playergames) {
        this.playergames = playergames;
    }
}